import styles from "./Detail.module.scss";
import Drawer from "@renderer/components/drawer";

import {
    getAutoMakeFriendDetail,
    getAutoMakeFriendDetailList,
    exportAutoMakeFriendDetail,
} from "@renderer/ajax/api/autoAddBuddy";
import { defineComponent, reactive, watch } from "vue";
import { useExpose } from "@renderer/utils";
import {
    ElMessage,
    ElTable,
    ElTableColumn,
    ElImage,
    ElIcon,
    ElEmpty,
    ElTooltip,
    ElForm,
    ElFormItem,
    ElTag,
    ElInput,
    ElButton,
    ElDescriptions,
    ElSelect,
    ElOption,
    ElPagination,
    ElDescriptionsItem,
} from "element-plus";
import { QuestionFilled } from "@element-plus/icons-vue";
import { Picture as IconPicture } from "@element-plus/icons-vue";
import dayjs from 'dayjs'
import { toBuffer } from "@renderer/utils/utils";
import { WEICHAT_SRARUS_LIST } from "@renderer/enums/common";
const { ipcRenderer } = require("electron");
const fs = require("fs");

export default defineComponent({
    name: "Detail",
    setup(props, { emit, slots }) {
        const drawerData = reactive({
            visible: false,
            title: "活动标题",
            width: "860px",
        });
        const state = reactive({
            row: {},
            list: [],
            page: 1,
            pageSize: 15,
            total: 0,
            Phone: "",
            /** 添加状态 0~5 */
            status: 0,
            Data: {
                addTypeWeiChat: false,
                addTypeWeiWork: false,
                autoRemarks: true,
                autoRemarksMsg: "",
                createdAt: "",
                custTagList: [],
                id: "",
                phoneList: [],
                status: 0,
                title: "",
                verifyMessage: "",
            },
        });
        const onExport = async () => {
            const res: any = await exportAutoMakeFriendDetail({
                Id: state.Data.id,
                Title: state.Phone,
                status: state.status,
            });
            let params = {
                title: "请选择下载文件的目录",
                buttonLabel: "保存",
                pathName: `${state.Data.title || ''}_${dayjs(state.Data.createdAt).format('YYYY_MM_DD')}.xlsx`,
            };
            let buf = toBuffer(res);
            ipcRenderer.invoke("open-savebox", params).then((res) => {
                fs.writeFileSync(res.filePath, buf);
                res && ElMessage.success("导出成功");
            });
        };
        const onState = async (row: any) => {
            drawerData.visible = true;
            drawerData.title = `${row.title} (${row.statusMsg ?? "--"})`;
            state.row = row;
            const res: any = await Promise.all([
                getAutoMakeFriendDetail({ Id: row.id }),
                getAutoMakeFriendDetailList({
                    Id: row.id,
                    Phone: state.Phone,
                    Status: state.status,
                    page: state.page,
                    pageSize: state.pageSize,
                }),
            ]);
            const [ Data, List ] = res
            state.Data = Data;
            state.list = List?.data || []
            state.total = List.total || 0
        };
        const getList = async () => {
            const res: any = await getAutoMakeFriendDetailList({
                Id: state.row.id,
                Phone: state.Phone,
                Status: state.status,
                page: state.page,
                pageSize: state.pageSize,
            });
            state.list = res.data;
            state.total = res.total;
        };
        let timeout: any;
        const onSearch = () => {
            if (timeout) clearTimeout(timeout);
            timeout = setTimeout(() => {
                getList();
            }, 400);
        };
        const onSizeChange = (v: number) => {
            state.page = 1;
            getList();
        };
        const onCurrentChange = (v: number) => {
            getList();
        };
        let timer: any = null;
        // 开启定时器
        const startTimer = () => {
            console.log("开启定时器");
            timer = setInterval(() => {
                onState(state.row);
            }, 5000);
        };
        // 关闭定时器
        const closeTime = () => {
            console.log("关闭定时器");
            clearInterval(timer);
        };
        watch(
            () => drawerData.visible,
            (v) => {
                state.page = 1
                state.pageSize = 15
                state.Phone = ''
                state.status = 0
                if (v) {
                    startTimer()
                } else {
                    closeTime()
                }
            }
        );
        useExpose({
            onState,
        });
        const renderError = (status, msg) => {
            // 1 未发送， 2 已发送 3 发送失败 4 已通过 5 已是好友
            return (
                <>
                    {!msg ? (
                        <div class={styles.error}>{status}</div>
                    ) : (
                        <div class={styles.error}>
                            {status}
                            <ElTooltip effect="dark" content={msg} placement="top">
                                <ElIcon>
                                    <QuestionFilled />
                                </ElIcon>
                            </ElTooltip>
                        </div>
                    )}
                </>
            );
        };
        const renderTag = () => (
            <div class={styles["detail-render-tags"]}>
                {state.Data.custTagList?.length
                    ? state.Data.custTagList?.map((item) => (
                        <ElTag key={item.id} type={item.isDelete ? "info" : ""}>
                            {item.name}
                        </ElTag>
                    ))
                    : "无"}
            </div>
        );
        const renderInfo = (row: any) => (
            <div class={styles.column_info}>
                <ElImage
                    class={styles.avatar}
                    src={row.avatorUrl}
                    vSlots={{
                        error: () => (
                            <ElIcon class={styles.avatar}>
                                <IconPicture />
                            </ElIcon>
                        ),
                    }}
                />
                <div class={styles.column_info_name}>{row.phone}</div>
            </div>
        );
        return () => (
            <>
                <Drawer state={drawerData}>
                    {{
                        default: () => (
                            <div class={styles.drawer_content}>
                                <div class={styles.info}>
                                    <ElDescriptions column={1}>
                                        <ElDescriptionsItem label="客户标签：">
                                            {renderTag()}
                                        </ElDescriptionsItem>
                                        <ElDescriptionsItem label="验证消息：">
                                            {state.Data.verifyMessage || '--'}
                                        </ElDescriptionsItem>
                                        <ElDescriptionsItem label="自动备注：">
                                            {state.Data.autoRemarksMsg || '--'}
                                        </ElDescriptionsItem>
                                        <ElDescriptionsItem label="创建时间：">
                                            {state.Data.createdAt || '--'}
                                        </ElDescriptionsItem>
                                    </ElDescriptions>
                                </div>
                                <ElForm class={styles.search} inline={true}>
                                    <div class={styles.fun}>
                                        <ElFormItem label="手机号">
                                            <ElInput
                                                class={styles.inp}
                                                vModel={state.Phone}
                                                onInput={onSearch}
                                                clearable
                                                placeholder="请输入手机号搜索"
                                            />
                                        </ElFormItem>
                                        <ElFormItem label="添加状态">
                                            <ElSelect
                                                vModel={state.status}
                                                placeholder="全部状态"
                                                onChange={getList}
                                            >
                                                {WEICHAT_SRARUS_LIST.map((item) => {
                                                    return (
                                                        <ElOption label={item.label} value={item.value} />
                                                    );
                                                })}
                                            </ElSelect>
                                        </ElFormItem>
                                        <ElFormItem class={styles.export_btn_box}>
                                            <div class={styles.right_btn}>
                                                <ElButton
                                                    class={styles.export_btn}
                                                    type="primary"
                                                    onClick={onExport}
                                                >
                                                    导出
                                                </ElButton>
                                            </div>
                                        </ElFormItem>
                                    </div>
                                </ElForm>
                                <div class={styles.table}>
                                    <ElTable
                                        maxHeight={600}
                                        data={state.list}
                                        maxHeight={600}
                                        vSlots={{
                                            default: () => (
                                                <>
                                                    <ElTableColumn
                                                        label="手机号"
                                                        minWidth="120"
                                                        vSlots={{ default: ({ row }) => renderInfo(row) }}
                                                    />
                                                    <ElTableColumn
                                                        label="添加状态"
                                                        minWidth="120"
                                                        vSlots={{
                                                            default: ({ row }) =>
                                                                row.weiChatStatusMsg
                                                                    ? renderError(
                                                                        row.weiChatStatusMsg,
                                                                        row.weiChatErrorMsg
                                                                    )
                                                                    : "--",
                                                        }}
                                                    />
                                                    <ElTableColumn
                                                        label="发送时间"
                                                        minWidth="120"
                                                        vSlots={{
                                                            default: ({ row }) =>
                                                                row.weChatRequestedAt || "--",
                                                        }}
                                                    />
                                                    <ElTableColumn
                                                        label="添加时间"
                                                        minWidth="120"
                                                        vSlots={{
                                                            default: ({ row }) => row.weChatPassedAt || "--",
                                                        }}
                                                    />
                                                </>
                                            ),
                                            empty: () => <ElEmpty />,
                                        }}
                                    />
                                    <ElPagination
                                        class={styles.pagination}
                                        vModel:currentPage={state.page}
                                        vModel:pageSize={state.pageSize}
                                        page-sizes={[15, 30, 50, 100]}
                                        background
                                        layout="prev, pager, next, sizes, total"
                                        total={state.total}
                                        onSizeChange={onSizeChange}
                                        onCurrentChange={onCurrentChange}
                                    />
                                </div>
                            </div>
                        ),
                    }}
                </Drawer>
            </>
        );
    },
});
